package com.ning;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;

/*
@李子宁
Happy,happy everyday!
冲鸭！
2021/3/26

*/
public class QAJSONDemo {

    //private static final String access_token = "3c95d8c5a9574eccaef180a98543e8e7";
    //private static final String app_key ="1e96be407b3911eb8f1ab559dfc0980a";
    private static final String access_token = "4e0690a2dc09464aa31792d0972734b0";
    private static final String app_key ="f0bee6208de211eba2b70bcfc7abc4bc";

    private final static Charset UTF8 = StandardCharsets.UTF_8;


    public static byte[] hmac256(byte[] key, String msg) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, mac.getAlgorithm());
        mac.init(secretKeySpec);
        return mac.doFinal(msg.getBytes(UTF8));
    }

    public static String sha256Hex(String s) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] d = md.digest(s.getBytes(UTF8));
        return DatatypeConverter.printHexBinary(d).toLowerCase();
    }

    public static void main(String[] args) {
        String timestamp = String.valueOf(System.currentTimeMillis()/1000L);
        System.out.println("timestamp: "+timestamp);
        //1.拼接请求数据和时间戳
        String httpBody = "{\"payload\":{\"event\":{\"payload\":{\"text\":\"标准问题\"},\"header\":{\"namespace\":\"TextRecognizer\",\"name\":\"Recognize\",\"messageId\":\"BasicStaic\"}}},\"header\":{\"qua\":{\"VN\":\"1.0.0.1\"}}}";
        Map<String,Object> parse = (Map<String, Object>) JSONObject.parse(httpBody);
        System.out.println(parse);
        String signingContent = JSONObject.toJSONString(parse) + timestamp;
        //2.获取Signature签名
        String signature = "";
        try {
            byte[] bytes = hmac256(access_token.getBytes("utf-8"), signingContent);
            signature  = DatatypeConverter.printHexBinary(bytes).toLowerCase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //3.在请求头中带上签名信息
        System.out.println("signature: " + signature);
        System.out.println(sendTencentPostAQData("https://gw.test.tvs.qq.com/customer-service/v20200513/events", app_key, access_token, parse));

    }

    public static StringBuffer sendTencentPostAQData(String url, String appKey, String accessToken, Map<String,Object> params){
        URL connect;
        StringBuffer data = new StringBuffer();
        String timestamp = String.valueOf(System.currentTimeMillis()/1000L);
        try {
            connect = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) connect.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("content-type", "application/json; charset=utf-8");
            String paramsStr = JSON.toJSONString(params);
            String signingContent = paramsStr + timestamp;
            byte[] bytes = hmac256(accessToken.getBytes("utf-8"), signingContent);
            String signature = DatatypeConverter.printHexBinary(bytes).toLowerCase();
            connection.setRequestProperty("Appkey",appKey);
            connection.setRequestProperty("DSN","iyunwen");
            connection.setRequestProperty("Timestamp",timestamp);
            connection.setRequestProperty("Signature",signature);
            System.out.println(signature);
            OutputStreamWriter paramOut = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
            paramOut.write(paramsStr);
            paramOut.flush();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            String line;
            while ((line = reader.readLine()) != null){
                data.append(line);
            }
            paramOut.close();
            reader.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return data;
    }
}
